package com.controller;

import java.util.List;
import java.util.Locale;

import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.MessageSource;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import com.entity.StudentInfo;
import com.service.StuService;

@Controller
public class StudentController {
	@Autowired
	private StuService stuService;
	@Autowired
	private MessageSource messageSource;
	@RequestMapping("/login")
	public String login(String stuName,String password,HttpSession session,ModelMap m) {
		StudentInfo login = stuService.login(stuName,password);
		if(login!=null) {
			session.setAttribute("session_student", login);
			return "main";
		}else {
			Locale locale = LocaleContextHolder.getLocale();
			String msg=messageSource.getMessage("loginerror",null, locale); 
			m.put("msg", msg);
			return "login";
		}
	}
	@RequestMapping("/students")
	public String getStuList(ModelMap map) {
		map.put("stuList", stuService.getList());
		return "user-pages/user-manager";
	}
	@GetMapping("/stu")
	public String goAddStu() {
		return "user-pages/user-add";
	}
	@PostMapping("/stu")
	public String addStu(@ModelAttribute("stu")StudentInfo stu) {
		stuService.addStu(stu);
		return "user-pages/user-add";
	}
	@GetMapping("/stus")
	public String stuList(ModelMap map) {
		List<StudentInfo> stuList = stuService.getList();
		map.put("stuList",stuList);
		return "user-pages/user-manager";
	}
	@GetMapping("/stu/{stuId}")
	public String goStuUpdate(Model map,@PathVariable("stuId") Integer stuId) {
		StudentInfo stuByid = stuService.getStuByid(stuId);
		map.addAttribute("stu",stuByid);
		return "user-pages/user-add";
	}
	@GetMapping("/delete/{stuId}")
	public String delete(ModelMap map,@PathVariable("stuId") Integer stuId) {
		stuService.delStu(stuId);
		return "redirect:/students";
	}
	
	@PutMapping("/stu")
	public String updateStu(StudentInfo stu,ModelMap map) {
		stuService.updateStu(stu);
		map.put("stu", stu);
		map.put("msg", "更新成功");
		return "user-pages/user-add";
	}
}
